package com.yangyongchao.resumedownload.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import com.yangyongchao.resumedownload.entires.FileInfo;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by 杨永超的电脑 on 2017/9/9.
 */

public class DownloadSrevice extends Service {

    public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+
            "/downloads";//根目录下的文件夹
    public static final String ACTION_START = "ACTION_START";
    public static final String ACTION_STOP = "ACTION_STOP";
    private String TAG = "DownloadSrevice";
    public static final int MSG_INIT = 0;

    @Override
    public int onStartCommand(Intent intent,int flags, int startId) {
        //获得Acitivity传来的参数
        if (ACTION_START.equals(intent.getAction())){
            FileInfo fileInfo = (FileInfo)intent.getSerializableExtra("fileInfo");
            Log.e(TAG,"Start"+fileInfo.toString());
            //启动初始化线程
            new InitThread(fileInfo).start();
        }else if (ACTION_STOP.equals(intent.getAction())){
            FileInfo fileInfo = (FileInfo)intent.getSerializableExtra("fileInfo");
            Log.e(TAG,"Stop"+fileInfo.toString());
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    Handler mHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_INIT:
                    FileInfo fileInfo = (FileInfo) msg.obj;
                    Log.e(TAG,"Init"+fileInfo);
                    break;
            }
        }

    };

    /**
     * 初始化的子线程
     */
    class InitThread extends Thread{

        private FileInfo mFileInfo = null;

        public InitThread(FileInfo mFileInfo){
            this.mFileInfo = mFileInfo;
        }
        public void run(){
            HttpURLConnection conn = null;
            RandomAccessFile raf = null;
            try{
                //连接网络文件
                URL url = new URL(mFileInfo.getUrl());//文件地址
                conn = (HttpURLConnection)url.openConnection();//打开连接
                conn.setConnectTimeout(3*1000);//超时时间
                conn.setRequestMethod("GET");//传输方式   下载不涉及或太文件传输加密
                int length = -1;
                if (conn.getResponseCode() == 200){
                    //获取本件长度
                    length = conn.getContentLength();
                }
                if (length <= 0){
                    return;
                }
                File dir = new File(DOWNLOAD_PATH);
                if (!dir.exists()){
                    //不存在则创建
                    dir.mkdir();
                }
                //在本地创建文件
                File file = new File(dir,mFileInfo.getFileName());
                //随机取传
                raf = new RandomAccessFile(file,"rwd");
                //设置文件长度
                raf.setLength(length);

                mFileInfo.setLength(length);
                mHandler.obtainMessage(MSG_INIT,mFileInfo).sendToTarget();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    conn.disconnect();
                    raf.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
